package ua_gov_energy_vkek_icelineacct.service;

import java.io.PrintWriter;
import java.io.StringWriter;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

/**
 * @author moroz
 */

/*
 * http://cxf.apache.org/docs/jax-rs-basics.html#JAX-RSBasics-Registeringcustomproviders
 * Putting @Provider annotation on the provider class is something that should lead to your provider
 * being registered with the runtime. CXF does not support this feature yet. 
 */
@Provider
public class MExcMapper
        implements ExceptionMapper<RuntimeException> {

    public static class ExceptionWrapper {

        private String message = "";
        private String stacktrace = "";

        public ExceptionWrapper(RuntimeException e) {
            this.message = e.getMessage();
            StringWriter sw = new StringWriter(15000);
            e.printStackTrace(new PrintWriter(sw));
            this.stacktrace = sw.toString();
        }

        public ExceptionWrapper() {
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String Message) {
            this.message = Message;
        }

        public String getStacktrace() {
            return stacktrace;
        }

        public void setStacktrace(String stacktrace) {
            this.stacktrace = stacktrace;
        }
    }

    @Override
    public Response toResponse(RuntimeException exception) {
        return Response.status(Response.Status.SERVICE_UNAVAILABLE)
                .entity(new ExceptionWrapper(exception))
                .type(MediaType.APPLICATION_JSON)
                .build();
    }
}
